#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
主窗口UI
"""

import tkinter as tk
from tkinter import ttk, messagebox
import time
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from game_core import GameCore
    from main import MiningSimulator

class MainWindow:
    """主窗口类"""
    
    def __init__(self, root: tk.Tk, game_core, app):
        self.root = root
        self.game_core = game_core
        self.app = app
        
        self.setup_window()
        self.create_widgets()
        self.setup_bindings()
        
        # 启动UI更新循环
        self.update_ui()
    
    def setup_window(self):
        """设置窗口"""
        self.root.title("挖矿模拟器：摸鱼版")
        self.root.geometry("900x700")
        self.root.resizable(True, True)
        
        # 设置窗口图标（如果有的话）
        try:
            # self.root.iconbitmap("icon.ico")
            pass
        except:
            pass
        
        # 设置关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
    
    def create_widgets(self):
        """创建控件"""
        # 主容器
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = tk.Label(
            main_frame, 
            text="🪙 挖矿模拟器：摸鱼版", 
            font=("Arial", 16, "bold"),
            fg="#333333"
        )
        title_label.pack(pady=(0, 20))
        
        # 顶部状态栏
        self.create_status_bar(main_frame)
        
        # 主要内容区域
        content_frame = ttk.Frame(main_frame)
        content_frame.pack(fill=tk.BOTH, expand=True)
        
        # 左侧面板
        left_frame = ttk.Frame(content_frame)
        left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 10))
        
        # 挖矿控制区域
        self.create_mining_control(left_frame)
        
        # 设备管理区域
        self.create_equipment_panel(left_frame)
        
        # 右侧面板
        right_frame = ttk.Frame(content_frame)
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 市场信息
        self.create_market_panel(right_frame)
        
        # 事件日志
        self.create_event_log(right_frame)
        
        # 底部按钮
        self.create_bottom_buttons(main_frame)
    
    def create_status_bar(self, parent):
        """创建状态栏"""
        status_frame = ttk.LabelFrame(parent, text="资产状态", padding="10")
        status_frame.pack(fill=tk.X, pady=(0, 10))
        
        # 状态信息网格
        status_grid = ttk.Frame(status_frame)
        status_grid.pack(fill=tk.X)
        
        # BTC余额
        ttk.Label(status_grid, text="💰 BTC:").grid(row=0, column=0, sticky=tk.W, padx=(0, 5))
        self.btc_label = ttk.Label(status_grid, text="0.00000000", font=("Consolas", 10))
        self.btc_label.grid(row=0, column=1, sticky=tk.W)
        
        # USD估值
        ttk.Label(status_grid, text="💵 USD估值:").grid(row=0, column=2, sticky=tk.W, padx=(20, 5))
        self.usd_label = ttk.Label(status_grid, text="$0.00", font=("Consolas", 10))
        self.usd_label.grid(row=0, column=3, sticky=tk.W)
        
        # 算力显示
        ttk.Label(status_grid, text="⚡ 总算力:").grid(row=1, column=0, sticky=tk.W, padx=(0, 5), pady=(5, 0))
        self.hashrate_label = ttk.Label(status_grid, text="0 H/s", font=("Consolas", 10))
        self.hashrate_label.grid(row=1, column=1, sticky=tk.W, pady=(5, 0))
        
        # 收益率
        ttk.Label(status_grid, text="📈 收益率:").grid(row=1, column=2, sticky=tk.W, padx=(20, 5), pady=(5, 0))
        self.earning_label = ttk.Label(status_grid, text="0.00000000/s", font=("Consolas", 10))
        self.earning_label.grid(row=1, column=3, sticky=tk.W, pady=(5, 0))
    
    def create_mining_control(self, parent):
        """创建挖矿控制面板"""
        mining_frame = ttk.LabelFrame(parent, text="⛏️ 挖矿控制", padding="10")
        mining_frame.pack(fill=tk.X, pady=(0, 10))
        
        # 挖矿按钮
        button_frame = ttk.Frame(mining_frame)
        button_frame.pack(fill=tk.X)
        
        self.mining_button = tk.Button(
            button_frame,
            text="🚀 开始BTC挖矿",
            font=("Arial", 12, "bold"),
            bg="#4CAF50",
            fg="white",
            padx=20,
            pady=10,
            command=self.toggle_mining
        )
        self.mining_button.pack(side=tk.LEFT)
        
        # 显示当前BTC价格
        ttk.Label(button_frame, text="BTC价格:").pack(side=tk.LEFT, padx=(20, 5))
        self.btc_price_label = ttk.Label(button_frame, text="$50,000", font=("Consolas", 10))
        self.btc_price_label.pack(side=tk.LEFT)
        
        # 挖矿状态
        status_frame = ttk.Frame(mining_frame)
        status_frame.pack(fill=tk.X, pady=(10, 0))
        
        self.mining_status = ttk.Label(status_frame, text="💤 矿机离线", font=("Arial", 10))
        self.mining_status.pack(side=tk.LEFT)
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            status_frame,
            variable=self.progress_var,
            maximum=100,
            length=200
        )
        self.progress_bar.pack(side=tk.RIGHT)
    
    def create_equipment_panel(self, parent):
        """创建设备面板"""
        equipment_frame = ttk.LabelFrame(parent, text="🔧 设备管理", padding="10")
        equipment_frame.pack(fill=tk.BOTH, expand=True)
        
        # 设备列表
        self.equipment_tree = ttk.Treeview(
            equipment_frame,
            columns=("level", "hashrate", "price"),
            show="tree headings",
            height=8,
            selectmode="extended"  # 明确设置选择模式
        )
        
        # 设置列
        self.equipment_tree.heading("#0", text="设备名称")
        self.equipment_tree.heading("level", text="等级")
        self.equipment_tree.heading("hashrate", text="算力")
        self.equipment_tree.heading("price", text="升级价格(USD)")
        
        self.equipment_tree.column("#0", width=150)
        self.equipment_tree.column("level", width=60)
        self.equipment_tree.column("hashrate", width=80)
        self.equipment_tree.column("price", width=120)
        
        self.equipment_tree.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
        
        # 绑定双击事件
        self.equipment_tree.bind("<Double-1>", self.on_equipment_double_click)
        
        # 操作提示
        tip_label = ttk.Label(
            equipment_frame,
            text="💡 双击设备升级",
            font=("Arial", 10),
            foreground="#666666"
        )
        tip_label.pack(pady=(5, 0))
    
    def create_market_panel(self, parent):
        """创建BTC市场面板"""
        market_frame = ttk.LabelFrame(parent, text="📈 BTC行情", padding="10")
        market_frame.pack(fill=tk.X, pady=(0, 10))
        
        self.market_tree = ttk.Treeview(
            market_frame,
            columns=("price", "change"),
            show="tree headings",
            height=2
        )
        
        self.market_tree.heading("#0", text="币种")
        self.market_tree.heading("price", text="价格 (USD)")
        self.market_tree.heading("change", text="涨跌幅")
        
        self.market_tree.column("#0", width=100)
        self.market_tree.column("price", width=100)
        self.market_tree.column("change", width=80)
        
        self.market_tree.pack(fill=tk.X)
    
    def create_event_log(self, parent):
        """创建事件日志"""
        log_frame = ttk.LabelFrame(parent, text="📰 事件日志", padding="10")
        log_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建文本框和滚动条
        text_frame = ttk.Frame(log_frame)
        text_frame.pack(fill=tk.BOTH, expand=True)
        
        self.event_text = tk.Text(
            text_frame,
            height=15,
            wrap=tk.WORD,
            bg="#f8f8f8",
            fg="#333333",
            font=("Consolas", 9)
        )
        
        scrollbar = ttk.Scrollbar(text_frame, orient="vertical", command=self.event_text.yview)
        self.event_text.configure(yscrollcommand=scrollbar.set)
        
        self.event_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 清空日志按钮
        clear_button = tk.Button(
            log_frame,
            text="🗑️ 清空日志",
            bg="#f44336",
            fg="white",
            padx=10,
            pady=2,
            command=self.clear_event_log
        )
        clear_button.pack(pady=(5, 0))
    
    def create_bottom_buttons(self, parent):
        """创建底部按钮"""
        button_frame = ttk.Frame(parent)
        button_frame.pack(fill=tk.X, pady=(10, 0))
        
        # 浮窗模式按钮
        floating_button = tk.Button(
            button_frame,
            text="🎯 切换浮窗模式",
            bg="#2196F3",
            fg="white",
            padx=15,
            pady=8,
            command=self.app.toggle_floating_mode
        )
        floating_button.pack(side=tk.LEFT)
        
        
        # 退出按钮
        quit_button = tk.Button(
            button_frame,
            text="❌ 退出游戏",
            bg="#795548",
            fg="white",
            padx=15,
            pady=8,
            command=self.on_closing
        )
        quit_button.pack(side=tk.RIGHT)
    
    def setup_bindings(self):
        """设置事件绑定"""
        # 监听游戏事件
        self.game_core.event_manager.add_listener("new_event", self.on_new_event)
    
    def toggle_mining(self):
        """切换挖矿状态"""
        if self.game_core.mining_active:
            self.game_core.stop_mining()
        else:
            self.game_core.start_mining()
    
    def get_btc_usd_value(self):
        """获取BTC的USD价值"""
        btc_amount = self.game_core.wallet["BTC"]
        btc_price = self.game_core.currencies["BTC"].price
        return btc_amount * btc_price
    
    def on_equipment_double_click(self, event):
        """设备双击事件"""
        self.upgrade_selected_equipment()
    
    def upgrade_selected_equipment(self):
        """升级选中的设备"""
        selected = self.equipment_tree.selection()
        if not selected:
            messagebox.showinfo("提示", "请先点击选择要升级的设备\n\n可以直接点击设备名称进行选择")
            return
        
        equipment_id = selected[0]
        equipment = self.game_core.equipment[equipment_id]
        current_btc = self.game_core.wallet["BTC"]
        upgrade_cost = equipment.price * (1.5 ** equipment.level)
        btc_price = self.game_core.currencies["BTC"].price
        upgrade_cost_usd = upgrade_cost * btc_price
        current_usd = current_btc * btc_price
        
        # 显示详细信息
        confirm_msg = f"确认升级 {equipment.name}？\n\n"
        confirm_msg += f"当前等级: Lv.{equipment.level}\n"
        confirm_msg += f"升级费用: ${upgrade_cost_usd:,.2f} ({upgrade_cost:.8f} BTC)\n"
        confirm_msg += f"当前余额: ${current_usd:,.2f} ({current_btc:.8f} BTC)\n\n"
        
        if current_btc < upgrade_cost:
            confirm_msg += "❌ 余额不足！"
            messagebox.showwarning("余额不足", confirm_msg)
            return
        else:
            confirm_msg += "✅ 余额充足，可以升级"
            
        result = messagebox.askyesno("确认升级", confirm_msg)
        if result:
            if self.game_core.upgrade_equipment(equipment_id):
                messagebox.showinfo("升级成功", f"{equipment.name} 已升级到 Lv.{equipment.level}！")
            else:
                messagebox.showwarning("升级失败", "升级过程中发生错误")
    
    def clear_event_log(self):
        """清空事件日志"""
        self.event_text.delete(1.0, tk.END)
        self.game_core.recent_events.clear()
    
    def on_new_event(self, message):
        """新事件回调"""
        self.event_text.insert(tk.END, message + "\n")
        self.event_text.see(tk.END)
    
    def update_ui(self):
        """更新UI显示"""
        try:
            # 更新资产显示
            wallet = self.game_core.wallet
            btc_amount = wallet['BTC']
            usd_value = self.get_btc_usd_value()
            btc_price = self.game_core.currencies["BTC"].price
            
            self.btc_label.config(text=f"{btc_amount:.8f}")
            self.usd_label.config(text=f"${usd_value:,.2f}")
            self.btc_price_label.config(text=f"${btc_price:,.0f}")
            
            # 更新算力和收益率
            total_hashrate = self.game_core.get_total_hashrate()
            earning_rate = self.game_core.get_earning_rate()
            
            self.hashrate_label.config(text=f"{total_hashrate:.1f} H/s")
            self.earning_label.config(text=f"{earning_rate:.8f}/s")
            
            # 更新挖矿状态
            if self.game_core.mining_active:
                self.mining_button.config(text="⏹️ 停止BTC挖矿", bg="#f44336")
                self.mining_status.config(text="⚡ 矿机运行中...")
                # 更新进度条动画
                current_progress = (self.progress_var.get() + 10) % 100
                self.progress_var.set(current_progress)
            else:
                self.mining_button.config(text="🚀 开始BTC挖矿", bg="#4CAF50")
                self.mining_status.config(text="💤 矿机离线")
                self.progress_var.set(0)
            
            # 更新设备列表
            self.update_equipment_display()
            
            # 更新市场行情
            self.update_market_display()
            
        except Exception as e:
            print(f"UI更新错误: {e}")
        
        # 继续更新循环
        self.root.after(500, self.update_ui)  # 500ms更新一次
    
    def update_equipment_display(self):
        """更新设备显示"""
        # 保存当前选中的项目
        selected_items = self.equipment_tree.selection()
        
        # 清空现有项目
        for item in self.equipment_tree.get_children():
            self.equipment_tree.delete(item)
        
        # 添加设备信息
        for eq_id, equipment in self.game_core.equipment.items():
            hashrate = equipment.hashrate * equipment.level if equipment.level > 0 else equipment.hashrate
            price = equipment.price * (1.5 ** equipment.level)
            btc_price = self.game_core.currencies["BTC"].price
            price_usd = price * btc_price
            
            self.equipment_tree.insert(
                "",
                tk.END,
                iid=eq_id,
                text=equipment.name,
                values=(equipment.level, f"{hashrate:.1f} H/s", f"${price_usd:,.2f}")
            )
        
        # 恢复选中状态
        for item_id in selected_items:
            try:
                self.equipment_tree.selection_add(item_id)
            except tk.TclError:
                # 如果项目不存在则忽略错误
                pass
    
    def update_market_display(self):
        """更新市场显示"""
        # 清空现有项目
        for item in self.market_tree.get_children():
            self.market_tree.delete(item)
        
        # 添加BTC市场信息
        currency = self.game_core.currencies["BTC"]
        change_text = f"{currency.change_rate:+.2f}%"
        
        self.market_tree.insert(
            "",
            tk.END,
            text=f"{currency.name} (BTC)",
            values=(f"${currency.price:,.2f}", change_text)
        )
    
    def show(self):
        """显示窗口"""
        self.root.deiconify()
    
    def hide(self):
        """隐藏窗口"""
        self.root.withdraw()
    
    def on_closing(self):
        """关闭窗口事件"""
        self.app.quit_game()
        self.root.quit()
        self.root.destroy()
    
    def quit(self):
        """退出应用"""
        self.root.quit()